package TestSystemUtil;

import java.io.*;
import java.net.*;

import javax.swing.JFrame;
import javax.swing.JOptionPane;

import TestSystemIO.*;

public class ClientUtil {
	
	public Socket connectToServer() {
		Socket connection = null;
		try {
			connection = new Socket("localhost", 6789);
			System.out.println("Connected to " + connection);
			connection.setTcpNoDelay(true);
		} catch (IOException ex) {
			JOptionPane.showMessageDialog(null, "Server not online", "Warning", JOptionPane.WARNING_MESSAGE);
		}
		return connection;
	}
		
	public InputThread makeInputThread(Socket connection, Object lockObj, Protocol protocol, JFrame frame) {
		try {
			BufferedReader input = new BufferedReader(new InputStreamReader(connection.getInputStream()));
			InputThread inputThread = new InputThread(input, lockObj, "Input Thread", protocol, frame);
			return inputThread;
		} catch (IOException e) {
			System.err.println("makeInputThread: " + e);
			return null;
		}
	}
	
	public OutputThread makeOutputThread(Socket connection, Object lockObj) {
		try {
			BufferedWriter output = new BufferedWriter(new OutputStreamWriter(connection.getOutputStream()));
			OutputThread outputThread = new OutputThread(output, lockObj, "Output Thread");
			return outputThread;
		} catch (IOException e) {
			System.err.println("makeOutputThread: " + e);
			return null;
		}
	}
	
	public void startSession(InputThread inputThread, OutputThread outputThread) {
		inputThread.start();
		outputThread.start();
	}
	
	public void finishSession(InputThread inputThread, OutputThread outputThread) {
		inputThread.interrupt();
		outputThread.interrupt();
	}
	
}
